package net.uhuijia.utils;

import java.util.Map;

import org.apache.log4j.Logger;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.ServiceHelper;
import cn.jiguang.common.connection.NativeHttpClient;
import cn.jiguang.common.resp.APIConnectionException;
import cn.jiguang.common.resp.APIRequestException;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.PushResult;
import cn.jpush.api.push.model.Options;
import cn.jpush.api.push.model.Platform;
import cn.jpush.api.push.model.PushPayload;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;

public class JPushUtils {
	public static Logger LOG = Logger.getLogger(JPushUtils.class);
	
	public static PushResult sendPushSingleAlias(String alias,String title,String alert,Map<String,Object> params,String secret,String appKey){
		PushPayload.Builder builder = buildPushObject_android_ios(params, title, alert);
		builder.setAudience(Audience.alias(alias));
		PushPayload payload = builder.build();
		return sendPush(payload,secret,appKey);
	}
	
	private static PushResult sendPush(PushPayload payload,String secret,String appKey){
		JPushClient client = getClient(secret,appKey);
		PushResult result= null;
		try {
			result = client.sendPush(payload);
			return result;
		} catch (APIConnectionException e) {
	        LOG.error("Connection error. Should retry later. ", e);
	    } catch (APIRequestException e) {
	    	System.out.println("HTTP Status: " + e.getStatus());
	    	System.out.println("Error Code: " + e.getErrorCode());
	    	System.out.println("Error Message: " + e.getErrorMessage());
	        LOG.error("Error response from JPush server. Should review and fix it. ", e);
	    }finally {
	    	client.close();
		}
		return result;
	}
	
	public static JPushClient getClient(String secret,String appKey){
			ClientConfig clientConfig = ClientConfig.getInstance();
			JPushClient client = new JPushClient(secret, appKey, null, clientConfig);
	        String authCode = ServiceHelper.getBasicAuthorization(appKey, secret);
	        NativeHttpClient httpClient = new NativeHttpClient(authCode, null, clientConfig);
	        client.getPushClient().setHttpClient(httpClient);
	        return client;
	}
	
	public static PushPayload.Builder buildPushObject_android_ios(Map<String,Object> params,String title,String alert) {
        return PushPayload.newBuilder()
                .setPlatform(Platform.android_ios()).setOptions(Options.newBuilder().setApnsProduction(true).build())
                .setNotification(buildNotification(params, title, alert));
     }
	
	public static Notification buildNotification(Map<String,Object> params,String title,String alert){
		Notification.Builder builder = Notification.newBuilder()
		.setAlert(alert)
		.addPlatformNotification(buildAndroidNotification(params, title))
		.addPlatformNotification(buildIosNotification(params));
		return builder.build();
	}
	
	
	public static AndroidNotification buildAndroidNotification(Map<String,Object> params,String title){
		AndroidNotification.Builder builder = AndroidNotification.newBuilder().setTitle(title);
		if(params!=null)
			for(String key:params.keySet())
				builder.addExtra(key, params.get(key)==null?"":params.get(key).toString());
		return builder.build();
	}
	
	public static IosNotification buildIosNotification(Map<String,Object> params){
		IosNotification.Builder builder = IosNotification.newBuilder().incrBadge(1);
		if(params!=null)
			for(String key:params.keySet())
				builder.addExtra(key, params.get(key)==null?"":params.get(key).toString());
		return builder.build();
	}
}
